/**
 * @name: TheUpload
 * @description: 上传组件封装
 * @upTime: 2023--11--21
 * @props { disabled }  Boolean     是否禁用上传控件
 * @props { len }       Number      上传数量
 * @props { maxSize }   Number      上传的文件大小     - 单位M
 * @props { accept }    Array       控制上传的文件类型
 * @props { fileList }  Array       数据集合
 * @props { extra }     String      额外的提示信息
 * @props { accept }    Array       限制上传的文件类型
 * @props { label }     String      Form.Item 标签的文本
 * @props { name }      String      Form.Item 字段名
 *
 **/
import {ProFormUploadButton,} from '@ant-design/pro-components';
import React, {useEffect, useState} from 'react';
import {message, Modal, Upload} from 'antd';

const BASE_URL = import.meta.env.VITE_APP_BASE_API
const RSnetToken = sessionStorage.getItem('RSnetToken')
const getBase64 = (file) =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
    });
const Index = (props) => {
    const [fileList, setFileList] = useState([]);
    const [len, setLen] = useState(5);
    const [disabled, setDisabled] = useState(false);
    const [maxSize, setMaxSize] = useState(5);
    const [extra, setExtra] = useState(false);
    const [previewOpen, setPreviewOpen] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    const [imageExtensions, setImageExtensions] = useState(['image/jpg', 'image/jpeg', 'image/png', 'image/webp', 'image/svg+xml']);

    useEffect(() => {
        props.len && setLen(props.len);
        props.disabled && setDisabled(props.disabled);
        props.maxSize && setMaxSize(props.maxSize);
        props.accept && setImageExtensions(props.accept);
        if (props.extra) {
            setExtra(props.extra)
        } else if (!extra) {
            setExtra('')
        } else {
            setExtra(`上传文件大小限制${maxSize}MB,文件格式限制 ${imageExtensions.map(item => item.split('/')[1])}`)
        }
    }, [])
    const normFile = (e) => {
        if (Array.isArray(e)) {
            return e;
        }
        setFileList(e?.fileList)
        if (e?.fileList.length) {
            return e?.fileList.map(item => {
                if (item.status === "done" && item.response) {
                    return item.response.data
                } else {
                    return item.url
                }
            }).toString();
        } else {
            return undefined
        }
    };

    const valueFile = (e) => {
        if (e) {
            let a = e?.split(',').map((item, index) => {
                return {
                    uid: `-${index + 1}`,
                    name: item.substring(item.lastIndexOf('/') + 1),
                    status: 'done',
                    url: item,
                }
            })
            if (fileList.length !== a.length) {
                setFileList(a)
            }
            return a
        } else {
            return []
        }
    }

    // 上传前置校验
    const checkFileSize = (file, fileList) => {
        if (!imageExtensions.includes(file.type)) {
            message.info(`上传文件格式不正确`)
            return Upload.LIST_IGNORE
        }
        if (file.size / 1024 / 1024 >= (maxSize || 5)) {
            message.info(`上传文件大小最大为${maxSize}MB`)
            return Upload.LIST_IGNORE
        }
    }
    const handlePreview = async (file) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj);
        }
        setPreviewImage(file.url || file.preview);
        setPreviewOpen(true);
        setPreviewTitle(file.name || file.url.substring(file.url.lastIndexOf('/') + 1));
    }
    // console.log()
    return (
        <>
            <ProFormUploadButton
                label={props.label || 'upload'}
                name={props.name || 'upload'}
                max={len}
                fieldProps={{
                    accept: imageExtensions.toString(),
                    className: 'ant-upload-select-hide',
                    name: 'file',
                    listType: 'picture-card',
                    headers: {RSnetToken},
                    disabled: disabled,
                    beforeUpload: checkFileSize,
                    onPreview: handlePreview,
                    // fileList: fileList
                }}
                rules={[
                    {
                        required: Boolean(props.required),
                        message: `请上传${props.label}`
                    },
                    {
                        validator: (_, value) => {
                            let str = null;
                            if (Array.isArray(value)) {
                                value?.some((item, index) => {
                                    if (item.type && !imageExtensions.includes(item.type)) {
                                        str = '上传文件格式不正确';
                                        return true
                                    }
                                    else if (item.size && item.size / 1024 / 1024 >= (maxSize || 5)) {
                                        str = `上传文件大小最大为${maxSize}MB`;
                                        return true
                                    }
                                })
                            }
                            if (str !== null){
                                return Promise.reject(new Error(str));
                            }
                            return Promise.resolve();
                        }
                    }
                ]}
                convertValue={(value)=>{
                    if (Array.isArray(value)) {
                        return value
                    }
                    else if (value) {
                        return value?.split(',').map((item, index) => {
                            return {
                                uid: `-${index + 1}`,
                                name: item.substring(item.lastIndexOf('/') + 1),
                                status: 'done',
                                url: item,
                            }
                        })
                    } else {
                        return []
                    }
                }}
                transform={(value)=>{
                    if (Array.isArray(value)) {
                        return value?.map(item => {
                            if (item.status === "done" && item.response) {
                                return item.response.data
                            } else {
                                return item.url
                            }
                        }).toString();
                    }
                    else {
                        return value
                    }
                }}
                action={BASE_URL + "management/oss/image/upload"}
                extra={extra}
            />
            {/*    <Form.Item*/}
            {/*        label={props.label ? (props.label || "Upload") : null}*/}
            {/*        name={props.name || 'Upload'}*/}
            {/*        valuePropName="fileList"*/}
            {/*        getValueFromEvent={normFile}*/}
            {/*        getValueProps={valueFile}*/}
            {/*        rules={props.rules ? props.rules : []}*/}
            {/*        extra={extra}*/}
            {/*    >*/}
            {/*        <Upload*/}
            {/*            action={BASE_URL + "management/oss/image/upload"}*/}
            {/*            listType="picture-card"*/}
            {/*            headers={{RSnetToken}}*/}
            {/*            fileList={fileList}*/}
            {/*            disabled={disabled}*/}
            {/*            beforeUpload={checkFileSize}*/}
            {/*            onPreview={handlePreview}*/}
            {/*        >*/}
            {/*            {*/}
            {/*                (fileList.length >= len || disabled) ? null : <div>*/}
            {/*                    <PlusOutlined/>*/}
            {/*                    <div style={{marginTop: 8}}>上传图片</div>*/}
            {/*                </div>*/}
            {/*            }*/}
            {/*        </Upload>*/}
            {/*    </Form.Item>*/}

            <Modal open={previewOpen} title={previewTitle} footer={null} onCancel={() => setPreviewOpen(false)}>
                <img
                    alt="preview"
                    style={{
                        width: '100%',
                    }}
                    src={previewImage}
                />
            </Modal>
        </>
    )
};

export default Index;
